package com.appengine.hotornot.ui.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.appengine.hotornot.entity.VoitesEntity;
import com.appengine.hotornot.ui.model.CandidateModel;
import com.appengine.hotornot.utils.CandidateComparator;

public class TopController extends AbstractUIController{
	private static final Logger log = Logger.getLogger(TopController.class
			.getName());
	public TopController(HttpServletRequest request) {
		super(request);		
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 7753833550134213612L;

	private List<CandidateModel> models = new ArrayList<CandidateModel>();
	
	@Override
	public void doJob() {		
		Document parse = null;
		try {
			final InputStream inputStream = getInputStream();
			parse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
		} catch (Exception e) {
			log.log(Level.SEVERE, "Parsing picasa responce fail",e);
			return;
		} 
		final NodeList entries = parse.getElementsByTagName("entry");
		long length = entries.getLength();		
		for(int i=0;i<length;i++)
		{
			final Node item = entries.item(i);
			final CandidateModel c = createCandidate(item);
			models.add(c);
		}
		fillVoites();
	}

	private void fillVoites()
	{
		final PersistenceManager pm = getPersistenceManager();
				
		final String query = "select from " + VoitesEntity.class.getName() + " order by voites";
		final List<VoitesEntity> items = (List<VoitesEntity>) pm.newQuery(query).execute();
		
		final Iterator<VoitesEntity> iterator = items.iterator();
		final List<CandidateModel> modelsNew = new ArrayList<CandidateModel>();
		while(iterator.hasNext())
		{
			final VoitesEntity next = iterator.next();
			final String pId = next.getPhotoId();
			
			final int size = models.size();
			for(int k=0;k<size;k++)
			{
				final CandidateModel candidateModel = models.get(k);
				final String photoId = candidateModel.getPhotoId();
				if(photoId!=null && photoId.equals(pId))
				{
					candidateModel.setVoites(next.getVoites());
					modelsNew.add(candidateModel);
					break;
				}
			}
		}
		final CandidateComparator comp = new CandidateComparator();
		models=modelsNew;
		Collections.sort(models, comp);
	}

	public List<CandidateModel> getModels() {
		return models;
	}	
}
